/*
 * This file is part of freewm.
 *
 * freewm is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * freewm is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with freewm.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "event.h"
#include "freewm.h"
#include "incs.h"
#include "module.h"

// Load modules for freewm.
void freewm_load_modules(void)
{
	logger("Loading freewm modules...");
	
	char path_h[MAXPATHLEN], path_g[MAXPATHLEN];
	
	// Assemble home and global directories.
	snprintf(path_h, sizeof(path_h), "%smodules/so/", path_home);
	snprintf(path_g, sizeof(path_g), "%smodules/so/", path_global);
	
	// Load all modules from each path.
	module_load_all(path_h);
	module_load_all(path_g);
}

// Execute everything we need to start freewm.
void freewm_start(void)
{
	logger("Starting freewm...");
	
	// Set home and global paths.
	snprintf(path_home, sizeof(path_home), "%s/.freewm/", getenv("HOME"));
	snprintf(path_global, sizeof(path_global), "%s/freewm/", DATADIR);
	
	// Connect to the X11 display.
	if (!(dpy = XOpenDisplay(NULL)))
	{
		fprintf(stderr, "freewm: cannot connect to X server\n");
		exit(1);
	}
	
	// Get the screen number and root window.
	screen = DefaultScreen(dpy);
	root = RootWindow(dpy, screen);
	
	// Initialize the event listener.
	event_start();
	
	// Load modules.
	freewm_load_modules();
	
	// Start the event loop.
	event_loop();
}

// Stop freewm, perform cleanups or whatever.
void freewm_stop(void)
{
	logger("Stopping freewm...");
	
	// Unload all modules.
	module_unload_all();
	
	// Exit.
	exit(0);
}

// Reload freewm and it's modules.
void freewm_reload(void)
{
	logger("Reloading freewm...");
	
	// Reload all modules.
	module_reload_all();
}
